package by.gravity.drive_track.fragments;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import by.gravity.common.cache.db.ModelCacheManager;
import by.gravity.common.fragment.CommonDialogFragment;
import by.gravity.drive_track.AppIntents;
import by.gravity.drive_track.R;
import by.gravity.drive_track.model.Favorite;

import com.google.gson.Gson;

public class MarkerActionDialogFragment extends CommonDialogFragment implements AppIntents {

	public static final String TAG = MarkerActionDialogFragment.class.getSimpleName();

	private ModelCacheManager mCacheManager;

	private LinearLayout mFavoriteLayout;

	private TextView mActionTextView;

	@Override
	public void onActivityCreated(Bundle arg0) {
		super.onActivityCreated(arg0);
		mCacheManager = ModelCacheManager.get(getActivity());
		mFavoriteLayout = (LinearLayout) getView().findViewById(R.id.favorite);
		mActionTextView = (TextView) getView().findViewById(R.id.action);
		Long markerID = getModel().getID();

		Favorite favorite = (Favorite) mCacheManager.getModelById(Favorite.class, markerID);
		if (favorite != null) {
			mActionTextView.setText(getString(R.string.remove_from_favorite));
		} else {
			mActionTextView.setText(getString(R.string.add_to_favorite));
		}

		mFavoriteLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				FavoriteNameDialogFragment fragment = new FavoriteNameDialogFragment();
				fragment.show(getFragmentManager(), FavoriteNameDialogFragment.TAG);
			}
		});

	}

	private Favorite getModel() {
		String json = getArguments().getString(ARG_FAVORITE_POINT);
		return new Gson().fromJson(json, Favorite.class);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		getDialog().setTitle(getString(R.string.choose_action));
		return inflater.inflate(R.layout.f_marker_action, null);
	}

	@Override
	protected void addIntentFilter(IntentFilter filter) {
		filter.addAction(ADD_TO_FAVORITE_INTENT);
		filter.addAction(CLOSE_DIALOG_INTENT);
	}

	@Override
	protected void onBroadcastReceive(Intent intent, String intentAction) {
		if (intentAction.equals(ADD_TO_FAVORITE_INTENT)) {
			String name = intent.getStringExtra(ARG_POINT_NAME);
			Favorite favorite = getModel();
			favorite.setName(name);
			mCacheManager.putModel(favorite);
			Toast.makeText(getActivity(), String.format(getString(R.string.point_success_added), name),
					Toast.LENGTH_SHORT).show();
			dismiss();

		} else if (intentAction.equals(CLOSE_DIALOG_INTENT)) {
			dismiss();
		}
	}

}
